import BTComposite from "../../Base/BTComposite";
import { NodeStatues } from "../../Enum";



export default class CompositeRandomSelector extends BTComposite {
    executeOrder: Array<number> = [];
    public onstart(): void {
        super.onstart();
        this.shuffle()

    }

    public getIndex(): number {
        return this.executeOrder[this.executeOrder.length - 1];
    }
    public shuffle() {
        this.executeOrder = []
        const indexList = Array.from({ length: this.children.length }, (_, i) => i);
        for (let i = indexList.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (indexList.length));
            this.executeOrder.push(indexList.splice(j, 1)[0]);
        }
    }
    public canExecute(): boolean {
        return this.executeOrder.length < this.children.length && this.statues !== NodeStatues.Success;
    }

    public onChildExecute(Statue: NodeStatues): void {
        switch (Statue) {
            case NodeStatues.Success:
                this.statues = NodeStatues.Success;

                break;
            case NodeStatues.Failed:
                this.executeOrder.pop();
                this.statues = NodeStatues.Failed;
                if (!this.executeOrder.length) {
                    this.statues = NodeStatues.Failed;
                } else {
                    this.statues = NodeStatues.Running
                }
                break;
            case NodeStatues.Running:
                this.statues = NodeStatues.Running;
                break;
            default:
                break;
        }
    }
}